home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Source Code / Libraries / VideoToolbox 94.11.17 / VideoToolboxSources / HexToBinary.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-09-16  |  2.0 KB  |  74 lines  |  [TEXT/KAHL]

  1. /*
  2. HexToBinary.c
  3. Two routines that translate back and forth between a binary object (some number
  4. of bytes at a specified address) and a string of hexadecimal digits. Two hex
  5. digits represent one binary byte.
  6.  
  7. PORTABILITY: Standard C.
  8.  
  9. HISTORY:
  10. 5/27/93 dgp wrote it, partly based on code I'd previously written for 
  11.             PixMapToPostScript.c 
  12. 6/15/93    dgp minor editing
  13. */
  14. #include "VideoToolbox.h"
  15. #include <assert.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18.  
  19. int HexToBinary(char *string,void *ptr)
  20. /* Fast translation of a hex string of arbitrary length. */
  21. {
  22.     register unsigned char *byte,c,dehex[256];
  23.     register unsigned long i;
  24.     size_t digits;
  25.  
  26.     for(i=0;i<sizeof(dehex);i++)dehex[i]=255;
  27.     for(i=0;i<10;i++)dehex[i+'0']=i;
  28.     for(i=0;i<6;i++)dehex[i+'a']=dehex[i+'A']=i+10;
  29.     digits=strlen(string);
  30.     byte=(unsigned char *)string;
  31.     for(i=0;i<digits;i++)if(dehex[*byte++]==255)return 1;    /*  Illegal character */
  32.     byte=(unsigned char *)ptr;
  33.     for(i=digits/2;i>0;i--){
  34.         c=dehex[*string++];
  35.         c<<=4;
  36.         c+=dehex[*string++];
  37.         *byte++ =c;
  38.     }
  39.     return 0;    /*  Success */
  40. }
  41.  
  42. char *BinaryToHex(size_t n,void *ptr,char *string)
  43. /*  Fast encoding of a specified number of bytes as a hex string. */
  44. /*  "string", if not NULL, must be able to hold at least 2*n+1 bytes. */
  45. {
  46.     register long i,j;
  47.     register unsigned short *word,hex[256];
  48.     register unsigned char *byte;
  49.     static const unsigned char c[]="0123456789abcdef";
  50.     long digits;
  51.     short oddAddress;
  52.  
  53.     assert(sizeof(*byte)==1);    /*  required by our algorithm */
  54.     assert(sizeof(*word)==2);    /*  required by our algorithm */
  55.     for(j=0;j<16;j++)for(i=0;i<16;i++)hex[(j<<4)+i]=(c[j]<<8)+c[i];
  56.     digits=2*n;
  57.     if(string==NULL){
  58.         string=(char *)malloc(digits+1);
  59.         if(string==NULL)return NULL;
  60.     }
  61.     oddAddress=(unsigned long)string%2;
  62.     if(oddAddress)string++;
  63.     word=(unsigned short *)string;
  64.     byte=(unsigned char *)ptr;
  65.     for(i=n;i>0;i--)*word++ = hex[*byte++];
  66.     if(oddAddress){
  67.         /* move back */
  68.         string--;
  69.         memmove(string,string+1,digits);
  70.     }
  71.     string[digits]=0;
  72.     return string;
  73. }
  74.